package com.java80.littlegame.service.game.handler;

import com.java80.littlegame.common.base.work.BaseHandler;
import com.java80.littlegame.common.base.work.Task;
import com.java80.littlegame.common.base.work.ThreadPools;
import com.java80.littlegame.common.msg.BaseMsg;
import com.java80.littlegame.common.msg.ProtoHelper;
import com.java80.littlegame.common.msg.ProtoList;
import com.java80.littlegame.common.msg.cluster.ClusterMessage;
import com.java80.littlegame.common.msg.cluster.DeskEndMessage;
import com.java80.littlegame.common.msg.cluster.GameStartMessage;
import com.java80.littlegame.common.msg.timer.DesktopExpridedMessage;
import com.java80.littlegame.service.game.desk.Desktop;
import com.java80.littlegame.service.game.desk.DesktopMgr;
import com.java80.littlegame.service.game.handler.subhandler.DesktopHandler;

public class GameHandler extends BaseHandler {
	private static GameHandler ins = new GameHandler();

	private GameHandler() {
	}

	public static GameHandler getInstance() {
		return ins;
	}

	private DesktopHandler desktopHandler = new DesktopHandler();

	@Override
	public Object onReceive(String obj) {
		// 收到消息 丢给actor处理
		BaseMsg baseMsg = ProtoHelper.parseJSON(obj.toString());
		switch (baseMsg.getType()) {
		case ProtoList.MSG_TYPE_CLUSTER:
			// 集群消息有可能没有发送者
			break;
		case ProtoList.MSG_TYPE_TIMER:
			// 定时调度消息有可能没有发送者
			break;
		default:
			// long senderUserId = baseMsg.getSenderUserId();

			break;
		}
		// TODO 先用线程池操作着，下次再改了*/
		ThreadPools.addTask(new Task() {
			@Override
			public void work() {
				processMsg(baseMsg);
			}
		});
		return null;
	}

	private void processMsg(BaseMsg msg) {
		long userId = msg.getSenderUserId();
		switch (msg.getCode()) {
		case ProtoList.MSG_CODE_GAME_START:
			desktopHandler.gameStart((GameStartMessage) msg);
			break;
		case ProtoList.MSG_CODE_DESKEND:
			desktopHandler.deskend((DeskEndMessage) msg, 1);
			break;
		case ProtoList.MSG_CODE_TIMER_DESKTOPEXPRIDED:
			DeskEndMessage de = new DeskEndMessage();
			DesktopExpridedMessage dem = (DesktopExpridedMessage) msg;
			de.setRoomId(dem.getRoomId());
			desktopHandler.deskend(de, 2);
			break;
		default:
			Desktop desktop = DesktopMgr.getDesktop(userId);
			if (desktop != null) {
				if (msg instanceof ClusterMessage) {
					desktop.onClusterMessage((ClusterMessage) msg);
				} else {
					desktop.onMessage(userId, msg);
				}
			}
			break;
		}

	}

}
